package com.lcj.workflow.service.impl;

import cn.hutool.core.map.MapUtil;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.lcj.common.exception.AochException;
import com.lcj.workflow.feign.OrderCommentApi;
import com.lcj.workflow.service.OrderCommentService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class OrderCommentServiceImpl implements OrderCommentService {
    @Resource
    private TaskService taskService;
    @Resource
    private OrderCommentApi orderCommentApi;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private HistoryService historyService;

    @Transactional
    @LcnTransaction
    public void acceptCommentAppeal(Map map) {
        HashMap orderId = orderCommentApi.searchCommentIdAndInstanceId(map);
        if (orderId != null && !orderId.isEmpty()) {
            String instanceId = MapUtil.getStr(orderId, "instanceId");
            if (instanceId == null) {
                throw new AochException("没有找到工作流实例");
            }
            Task task = taskService.createTaskQuery().processInstanceId(instanceId).includeProcessVariables().includeTaskLocalVariables().taskName("人工审核").singleResult();
            String userId = MapUtil.getStr(map, "userId");
            taskService.claim(task.getId(), userId);
            if (orderCommentApi.acceptAppeal(map) != 1) {
                throw new AochException("更新订单评价的user_id字段失败");
            }
        } else {

            throw new AochException("没有找到评价记录");
        }
    }


    @Transactional
    @LcnTransaction
    public void startCommentWorkflow(Map map) {
        Long orderId = MapUtil.getLong(map, "orderId");
        HashMap<String, Object> form = new HashMap<>();
        form.put("orderId", orderId);
        HashMap commentIdAndInstanceId = orderCommentApi.searchCommentIdAndInstanceId(form);
        if (commentIdAndInstanceId != null && !commentIdAndInstanceId.isEmpty()) {
            String instanceId = MapUtil.getStr(commentIdAndInstanceId, "instanceId");
            if (instanceId != null) {
                throw new AochException("该订单评价已经存在工作流实例");
            }

            Long commentId = MapUtil.getLong(commentIdAndInstanceId, "id");
            map.put("commentId", "" + commentId);
            //开启工作流，获取processInstanceId
            String getProcessInstanceId = runtimeService.startProcessInstanceByKey("comment", map).getProcessInstanceId();
            map.put("instanceId", getProcessInstanceId);
            map.put("detail", MapUtil.getStr(map, "reason"));
            //插入到tb_order_comment记录
            if (orderCommentApi.startWorkflow(map) != 1) {
                throw new AochException("更新订单评价instance_id字段失败");
            }
        } else {
            throw new AochException("没有找到评价记录");
        }
    }

    public HashMap searchAppealContent(String instanceId, boolean isEnd) {
        if (!isEnd) {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).includeProcessVariables().singleResult();
            if (processInstance == null) {
                throw new AochException("没有找到工作流实例");
            }
            Map map1 = processInstance.getProcessVariables();
            String str1 = MapUtil.getStr(map1, "reason");
            String str2 = MapUtil.getStr(map1, "note");
            HashMap<Object, Object> hashMap1 = new HashMap<>();
            hashMap1.put("reason", str1);
            hashMap1.put("note", str2);
            return hashMap1;
        }

        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(instanceId).includeProcessVariables().singleResult();
        if (historicProcessInstance == null) {
            throw new AochException("没有找到工作流实例");
        }
        Map map = historicProcessInstance.getProcessVariables();
        String reason = MapUtil.getStr(map, "reason");
        String note = MapUtil.getStr(map, "note");
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("reason", reason);
        hashMap.put("note", note);
        return hashMap;
    }


    @Transactional
    @LcnTransaction
    public void handleCommentAppeal(Map a) {
        String orderId = MapUtil.getStr(a, "instanceId");
        String var3 = MapUtil.getStr(a, "userId");
        Task task = taskService.createTaskQuery().processInstanceId(orderId).includeProcessVariables().includeTaskLocalVariables().taskName("人工审核").taskAssignee(var3).singleResult();
        if (task == null) {
            throw new AochException("没有找到审批任务");
        }
        var3 = MapUtil.getStr(a, "result");
        String var4 = MapUtil.getStr(a, "reason");
        var4 = MapUtil.getStr(a, "note");
        taskService.setVariable(task.getId(), "result", var3);
        taskService.setVariable(task.getId(), "note", var4);
        a.remove("instanceId");
        int var6 = "同意".equals(var3) ? 4 : 3;
        a.put("status", Integer.valueOf(var6));
        if (orderCommentApi.updateStatus(a) != 1) {
            throw new AochException("更新评价状态失败");
        }
        taskService.complete(task.getId());
    }
}